<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :label-width="90" :model="searchForm" inline>
          <Form-item label="模板名称" prop="table_name">
            <label>
              <Input
                v-model="searchForm.table_name"
                clearable
                placeholder="请输入模板名称"
                style="width: 200px"
                type="text"
              />
            </label>
          </Form-item>
          <Form-item class="br" style="margin-left:-35px;">
            <Button icon="ios-search" type="primary" @click="handleSearch">搜索</Button>
            <Button @click="handleReset">重置</Button>
          </Form-item>
        </Form>
      </Row>
      <Row class="operation">
        <Button icon="md-add" type="primary" @click="add">添加</Button>
        <Button icon="md-refresh" @click="getDataList">刷新</Button>
      </Row>
      <Row>
        <Table
          ref="table"
          :columns="columns"
          :data="data"
          :loading="loading"
          border
        >
          <template slot="action" slot-scope="{ row }">
            <a
              class="edit"
              size="small"
              style="color:#2d8cf0;font-size: 12px;"
              type="text"
              @click="exportTemplate(row)"
            >导出模板</a>
            <Divider type="vertical"/>
            <a
              class="edit"
              size="small"
              style="color:#2d8cf0;font-size: 12px;"
              type="text"
              @click="edit(row)"
            >编辑</a>
            <Divider type="vertical"/>
            <a class="del" style="color:#ed4014;font-size: 12px;" @click="remove(row)">删除</a>
          </template>
        </Table>
      </Row>
    </Card>
    <Modal v-model="modalVisible" :mask-closable="false" :title="modalTitle" :width="770">
      <Form
        ref="form"
        :label-width="100"
        :model="form"
        :rules="formValidate"
        inline
        label-position="left"
      >
        <FormItem label="模板名称：" prop="table_name">
          <label>
            <Input v-model="form.table_name" clearable placeholder="请输入模板名称" style="width:250px"/>
          </label>
        </FormItem>
      </Form>
      <vxe-toolbar>
        <template v-slot:buttons>
          <vxe-button status="success" @click="insertEvent(-1)">新增</vxe-button>
          <vxe-button status="danger" @click="$refs.xTable.removeCheckboxRow()">删除选中</vxe-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        :data="tableData"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true, icon: 'fa fa-pencil'}"
        :edit-rules="validRules"
        border
        class="my_table_insert"
        highlight-cell
        keep-source
        max-height="400"
      >
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column
          :edit-render="{name: 'input', defaultValue: ''}"
          field="column_name"
          title="列名"
        ></vxe-table-column>
        <vxe-table-column
          :edit-render="{name: '$select', options: columnType}"
          field="column_type"
          title="数据类型"
        ></vxe-table-column>
      </vxe-table>
      <div slot="footer">
        <Button type="text" @click="modalVisible=false">取消</Button>
        <Button :loading="submitLoading" type="primary" @click="handleSubmit">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {accountImportTemplateList, destroy, store, update} from '../../../api/account'
import expandRow from './table-expand'

export default {
  components: {
    expandRow,
  },
  data() {
    return {
      loading: true, // 表单加载状态
      modalType: 0, // 添加或编辑标识
      modalVisible: false, // 添加或编辑显示
      modalTitle: '', // 添加或编辑标题
      searchForm: {
        table_name: ''
      },
      form: {
        table_name: '',
      },
      // 表单验证规则
      formValidate: {
        table_name: [
          {required: true, message: '名称不能为空', trigger: 'blur'},
        ],
      },
      submitLoading: false, // 添加或编辑提交状态
      columns: [
        {
          type: 'index',
          width: 60,
          align: 'center',
        },
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row,
              },
            })
          },
        },
        {
          title: '模板名称',
          key: 'table_name',
          minWidth: 120,
        },
        {
          title: '最近修改时间',
          key: 'updated_at',
          minWidth: 120,
          sortable: true,
        },
        {
          title: '操作',
          slot: 'action',
          width: 200,
          fixed: 'right',
          align: 'center'
        }
      ],
      data: [], // 表单数据
      tableData: [],
      columnType: [
        {
          label: '文本',
          value: 'string',
        },
        {
          label: '金额',
          value: 'amount',
        },
        {
          label: '日期',
          value: 'date',
        },
        {
          label: '数字',
          value: 'number',
        },
        {
          label: '百分比',
          value: 'percentage',
        },
        {
          label: '整数',
          value: 'integer',
        },
      ],
      validRules: {
        column_name: [{required: true, message: '列名必须填写'}],
        column_type: [{required: true, message: '数据类型必须填写'}],
      },
    }
  },
  methods: {
    init() {
      this.getDataList()
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getDataList()
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      // 重新加载数据
      this.getDataList()
    },
    getDataList() {
      this.loading = true
      accountImportTemplateList(this.searchForm).then((res) => {
        this.loading = false
        if (res.data) {
          this.data = res.data
        }
      })
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const {
            insertRecords,
            removeRecords,
            updateRecords,
          } = this.$refs.xTable.getRecordset()
          if (this.modalType === 0) {
            delete this.form.id
            store({
              table_name: this.form.table_name,
              insert: insertRecords,
            }).then((res) => {
              this.submitLoading = false
              if (res.data) {
                this.getDataList()
                this.modalVisible = false
              }
              this.$Message.success(res.message)
            })
          } else {
            // 编辑
            update({
              insert: insertRecords,
              update: updateRecords,
              delete: removeRecords,
              tableNameBefore: this.form.table_name_before
            }, this.form.table_name).then(res => {
              this.submitLoading = false
              if (res.data) {
                this.getDataList()
                this.modalVisible = false
              }
              this.$Message.success(res.message)
            })
          }
        }
      })
    },
    add() {
      this.modalType = 0
      this.modalTitle = '添加'
      this.$refs.form.resetFields()
      delete this.form.id
      this.tableData = []
      this.modalVisible = true
    },
    edit(v) {
      this.modalType = 1
      this.modalTitle = '编辑'
      this.$refs.form.resetFields()
      // 转换null为""
      for (const attr in v) {
        if (v[attr] === null) {
          v[attr] = ''
        }
      }
      const str = JSON.stringify(v)
      this.form = JSON.parse(str)
      this.tableData = v.data
      this.modalVisible = true
    },
    remove(v) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '您确认要删除 ' + v.table_name + ' ?',
        loading: true,
        onOk: () => {
          // 删除
          destroy(v.table_name).then(res => {
            this.$Modal.remove()
            if (res.data) {
              this.getDataList()
            }
            this.$Message.success(res.message)
          })
        },
      })
    },
    exportTemplate(row) {
      window.location.href =
        '/api/exportAccountTemplate?tableName=' + row.table_name
    },
    async insertEvent(row) {
      const record = {}
      const {row: newRow} = await this.$refs.xTable.insertAt(record, row)
      await this.$refs.xTable.setActiveCell(newRow, 'column_name')
    },
  },
  mounted() {
    this.init()
  },
}
</script>
<style lang="less">
.search {
  .operation {
    margin-bottom: 2vh;
  }

  .select-clear {
    margin-left: 10px;
  }

  .drop-down {
    margin-left: 5px;
  }
}

.vxe-select--panel {
  z-index: 9999 !important;
}

.my_table_insert .vxe-body--row.is--new {
  background-color: #f1fdf1;
}

.vxe-table--header {
  width: 100% !important;
}

.vxe-table--empty-placeholder {
  top: 48px !important;
}
</style>
